<?php
/**
* The sidebar menu for this mod.  Lib.php page_setup function will reset all of the sidebars
*    so that this replaces both the blog sidebar & the file sidebar.
*
* @package folio
* @param string $username The url-usable name of the page's owner.  Will find if not set. OPTIONAL
* @param int $page_owner The ident for the page's owner.
**/
global $CFG;
global $page_owner;
global $username;
global $profile_id;

// Load library files
if ( !isset ( $FOLIO_CFG) ) {
    // Note to self: do not change to require_once, as this config file needs to be forced to load.
    require $CFG->dirroot . 'mod/folio/config.php';
}
require_once 'control/feeds.php';

// Grab the username of the page owner.
if ( !isset( $username ) ) {
    if ( isset( $page_owner ) ) {
        $user = folio_user::SelectWhereIdent( $page_owner );
    } elseif ( isset( $profile_id ) ) {
        $user = folio_user::SelectWhereIdent( $profile_id );    
    }
}

// Name is not guaranteed to be linkable, unlike the username.
$displayname = run("profile:display:name", $page_owner);
$url = url;
$body = '';

// context isn't set on all pages, esp the 1st one.
if ( defined( 'context' ) ) {
    $context = context;
} else {
    $context = '';
}


// Begin building the main links to the page owner's content.
//      Only show if this isn't "us" - aka, not = the current user.
if (isset($page_owner) && $page_owner != -1 && $page_owner != 0 && $page_owner <> $_SESSION['userid']) {
    
    $run_result .= folio_menu_inbox($username);
    
    $body = "<li id='sidebar_folio'><h2><a href='{$url}activity/user/{$username}/html/all/all/1'>" . $displayname .
        "</a> <a href='{$url}activity/user/{$username}/rss/all/all/1:" . folio_createhash( $_SESSION['userid'] ) .
        "'><img border=0 src='{$url}mod/folio/image/feed.png' alt='feed'/></a></h2>";

    // Side-bar links
    $body .= "<ul>";
    
    if ( !in_array( 'profile', $FOLIO_CFG->disabled_foliomenuitems ) ) {
        $body .= "<li><a href='{$url}{$username}/'>Profile</a></li>\n\n";
    }
    if ( !in_array( 'weblog', $FOLIO_CFG->disabled_foliomenuitems ) ) {
        $body .= folio_menu_sidemenu_blog( $url, $username, $page_owner ) . "\n\n";
    }
    if ( !in_array( 'files', $FOLIO_CFG->disabled_foliomenuitems ) ) {
        $body .= "<li><a href=\"$url{$username}/files/\">Files</a></li>\n\n";
    }
    if ( !in_array( 'wiki', $FOLIO_CFG->disabled_foliomenuitems ) ) {
        $body .= folio_menu_sidemenu_wiki( $url, $username, $page_owner ) . "\n\n";
    }
    $body .= '</ul></li>';
    
    // Build & Display to the screen.
    /*
    $run_result .= templates_draw(array(
            'context' => 'sidebarholder',
            'title' => $title,
            'body' => $body,
            )
        );
        */
    $run_result .= $body;
    
} elseif ( $context == 'folio_page_view' ) {
    // Viewing our own page.
    // Show wiki tree
    if ( !in_array( 'wiki', $FOLIO_CFG->disabled_foliomenuitems ) ) {
        $run_result .= "<li id='sidebar_folio'><h2>Pages</h2><ul>\n\n" .
            folio_menu_sidemenu_wiki( $url, $username, $page_owner ) . 
            "\n</ul></li>\n\n";
    }    
    $run_result .= folio_menu_inbox($username);
    
} elseif ( logged_on && $page_owner == $_SESSION['userid']) {
    // Add Recent Activity if we're logged in & looking at our own pages.
    // Build the last-logon side menu 
    $run_result .= folio_menu_inbox($username);
} 

    // Remove Unwanted menu items
    folio_prunetopmenu();

/**
* Return the code for the blog menu entry
**/
function folio_menu_sidemenu_blog( $url, $username, $page_owner ) {
    $body = '';
    
    if (run("users:type:get",$page_owner) == "person") {
        $personalWeblog = gettext("Blog");
        $body .= <<< END
            <li><a href="$url{$username}/weblog/">$personalWeblog</a></li>
END;
    } else if (run("users:type:get",$page_owner) == "community") {
        $communityWeblog = gettext("Community blog");
        $body .= <<< END
            <li><a href="$url{$username}/weblog/">$communityWeblog</a></li>
END;
    }

    return $body;
}


/**
* Return links for the revised menu content links
**/
function folio_menu_sidemenu_wiki( $url, $username, $userid ) {
    // Add wiki entry
    require_once("control/tree.php");
    
    // Depends upon the following globals being set.
    global $page_ident;
    global $comment_on_username;
    global $comment_on_name;
    global $page_title;
    global $CFG;
    global $FOLIO_CFG;
    global $profile_id;
    
    $prefix = $CFG->prefix;
    
    
    if ( isset( $page_ident ) ) {
        // If a page_ident value is defined, we are looking at a sub-page.
        $pi = $page_ident;
        $pt = $page_title;
        return '<li>' . folio_control_tree($pi, $pt, $username, $pi);   
    } else {
        // Find the name of the Root page.
        $pages = recordset_to_array(
            get_recordset_sql("SELECT w.user_ident, w.* FROM {$prefix}folio_page w " .
                "INNER JOIN {$prefix}folio_page_security p " .
                "ON w.security_ident = p.security_ident " .
                "WHERE w.user_ident = {$userid} and w.newest = 1 and w.page_ident = w.parentpage_ident AND " . 
                folio_page_security_where( 'p', 'w', 'read', $profile_id ) )
            );          
        if ( $pages ) {
            $page = $pages[$userid];
            $pt = $page->title;
            $pi = $page->page_ident;
            return '<li>' . folio_control_tree($pi, $pt, $username, -1);
        } else {
            // No root page.
            return '<li><a href="' . $CFG->wwwroot . $username  . '/page/">Wiki Page</a>';
        }
    }

}

/**
* Return links for the side menu
*
* Builds the number of events since the user's last logon
**/
function folio_menu_inbox($username) {
    global $_SESSION;
    global $CFG;

    $run_result = '';
    $url = url;

   /*

    // Test to see if we need to re-check the amount of activity since last log-on.
    //    If not, just use the cached values created when 1st checked this session.
    if ( !isset( $_SESSION['folio_events_all'] ) ) {


        // Grab the number of events since last logon
        $events = recordset_to_array( get_recordset_sql( 
            "SELECT count(*) as rc_index, count(*) as rowcount FROM " . 
            $CFG->prefix . "folio_rss ".
            "WHERE created >= {$_SESSION['folio_lastlogon']} " ) );
                if ( !$events ) {
                    // No events
                    $_SESSION['folio_events_all'] = 0;
                } else {
                    $events =  array_pop($events);
                    $_SESSION['folio_events_all'] = $events->rowcount;
        }

        // Grab the number of events in friends & joined communities since last logon
        $activity = recordset_to_array( get_recordset_sql( 
            "SELECT count(*) as rc_index, count(*) as rowcount FROM " . 
            $CFG->prefix . "folio_rss ".
            "WHERE created >= {$_SESSION['folio_lastlogon']} AND "  .
            folio_feeds_buildWhere( 'fac', $_SESSION['userid'], $_SESSION['userid'], array('all'), array() )
            ) );

                if ( !$activity ) {
                    // No events
                    $_SESSION['folio_events_fac'] = 0;
                } else {
                    $activity =  array_pop($activity);
                    $_SESSION['folio_events_fac'] = $activity->rowcount;
                }
    }
    
    // $_SESSION['folio_events_fac']    (<b>{$_SESSION['folio_events_all']} new</b>)
*/
    // Build the html for the side-menu to return
    $run_result .= "<li id=\"inbox\">" .
        templates_draw(array('context' => 'sidebarholder', 'title' => 'Recent Activity',
            'body' => "<ul>"
            )); 
    $run_result .= "<li><a href='{$url}activity/inbox/{$username}/html/all/all/1'>Inbox</a></li>";
    $run_result .= "<li><a href='{$url}activity/fac/{$username}/summary/all/all/1'>Friends & Communities</a></li>";
    $run_result .= "</ul></li>";

    return $run_result;
}

/**
* Used to generate a 'where' clause for a folio page retrieval operation. Used by tree.php.
* Note that by using this where clause, and running an innner join operation, you are opening the possiblity
*     of retrieving duplicate records.  To compensate, only retrieve the page values & slap a distinct on top
*    of the query.  It's not the most elegant way of handling dups, but should avoid triggering any bugs
*    from ADODB's keying of returned values by ID.
*
* @uses isloggedin
* @uses $SESSION['userid']
* @param mixed $tableprefix The alias for the permission table being used.
* @param mixed $tableprefix The alias for the page table being used.
* @param string $level The level of permission that we're looking for...  Values (read, write, owner).
* @param int $profile_id The owner of the pages we're looking at.
* @return A where condition usable for getting content via joining folio_page and folio_page_security
*/
function folio_page_security_where( $tp_permission, $tp_page, $level, $profile_id ) {
    // TODO: Validate input.
    //$user_ident = required_param( $user_ident, int);
    global $CFG;
    $userid = array($_SESSION['userid']);

    // Build userid list, giving us a list of memberships.
    if ( isloggedin() ) {

        // Grab community IDs for friends.
        $groupid = recordset_to_array(
            get_recordset_sql( "SELECT * FROM " . $CFG->prefix . "friends f " .
                " INNER JOIN " . $CFG->prefix . "users u on f.friend = u.ident " .
                "WHERE f.owner = " . $_SESSION['userid'] . " AND u.user_type='community' ") );

        if ( !!$groupid ) {
            foreach ( $groupid as $id ) {
                $userid[] = $id->friend;
            }
        }

        // Grab community IDs for owned communities
        $groupid = recordset_to_array(
            get_recordset_sql( "SELECT * FROM " . $CFG->prefix . "users ".
                "WHERE user_type = 'community' AND owner = " . $_SESSION['userid'] ) );

        if ( !!$groupid ) {
            foreach ( $groupid as $id ) {
                $userid[] = $id->ident;
            }
        }
    }

    // Convert array userid list to a sql-able where clause.
    $userid = '(' . implode(', ', $userid ) . ')';

    // Validate
    if (!($level == 'read' | $level == 'write' | $level == 'owner' )) {
        error(' You can only pass the values read/write/owner to folio_page_security_where in mod\folio\lib.php ');
    }

    // Note: Use all upper-case for constants in sql.
    if (!isloggedin() && $level=='read') {

        return " ( $tp_permission.accesslevel = 'PUBLIC' " .
            " OR $tp_permission.accesslevel = 'MODERATED' ) ";

    } elseif (!isloggedin() && ($level=='write' || $level='owner') ) {

        return " ( $tp_permission.accesslevel = 'PUBLIC' ) ";

    } elseif ($level == 'read') {

        return " ( $tp_permission.accesslevel = 'PUBLIC' " .
            " OR $tp_permission.accesslevel = 'MODERATED' " .
            " OR ( $tp_permission.accesslevel = 'PRIVATE' AND $tp_page.user_ident IN $userid ) ) ";

    } elseif ($level == 'write' | $level == 'owner') {

        return " ( $tp_permission.accesslevel = 'PUBLIC' " .
            "OR ( $tp_permission.accesslevel = 'MODERATED' AND $tp_page.user_ident IN $userid ) " .
            "OR ( $tp_permission.accesslevel = 'PRIVATE' AND $tp_page.user_ident IN $userid ) ) ";

    }

}

?>